<?php

/**
 * @Author: 网名
 * @Date:   2018-06-03 10:12:18
 * @Last Modified by:   网名
 * @Last Modified time: 2018-06-03 16:32:10
 */
namespace app\admin\controller;
use app\admin\model\PluginModel;
use think\Db;

class Plugin extends Base {

    public function _initialize()
    {
        parent::_initialize();
        //  更新插件
        $this->insertPlugin($this->scanPlugin());
    }

    public function index(){
    	if(IS_AJAX){
	    	$param = input('param.');
	        $limit = $param['pageSize'];
	        $offset = ($param['pageNumber'] - 1) * $limit;
	        $where = [];
	    	$plugin = new PluginModel();
	    	$selectResult = $plugin->getPluginByWhere($where, $offset, $limit);

	    	// var_dump($selectResult);exit;

	        foreach($selectResult as $key=>$vo){
	        	// $selectResult[$key]['logo'] = PLUGIN_PATH.$vo['type'].'/'.$vo['code'].'/logo.jpg';
	        	$selectResult[$key]['operate'] = showOperate($this->makeButton($vo));
	        }

	        $return['total'] = $plugin->getAllPlugin($where);  //总数据
	        $return['rows'] = $selectResult;

	        return json($return);
	    }
	    return $this->fetch();
    }


     /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton($vo)
    {
    	if($vo['status']==1) {
    		return [
            '配置' => [
                'auth' => 'plugin/setting',
                'href' => url('plugin/setting', ['type' => $vo['type'],'code'=>$vo['code']]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste'
            ],
            '卸载' => [
                'auth' => 'users/unstall',
                'href' => "javascript:installPlugin('".$vo['type']."','".$vo['code']."',0);",
                'btnStyle' => 'danger',
                'icon' => 'fa fa-trash-o'
            ]
        ];

    	}else{
    		return [
	            '一键安装' => [
	                'auth' => 'plugin/install',
	                'href' => "javascript:installPlugin('".$vo['type']."','".$vo['code']."',1);",
	                'btnStyle' => 'primary',
	                'icon' => 'fa fa-paste'
	            ]
	        ];
    	}
        
    }

    /**
     * 插件安装卸载
     */
    public function install(){
        $condition['type'] = input('param.type');
        $condition['code'] = input('param.code');
        $update['status'] = input('param.install');
        $model = M('plugin');
        
        // echo $update['status'];exit;
        
        //卸载插件时 删除配置信息
        if($update['status']==0){
            $row = M('plugin')->where($condition)->delete();
        }else{

            $row = $model->where($condition)->update($update);
        }
//        $row = $model->where($condition)->save($update);
        //安装时更新配置信息(读取最新的配置)
        if($condition['type'] == 'payment' && $update['status']){
            $file = PLUGIN_PATH.$condition['type'].'/'.$condition['code'].'/config.php';
            $config = include $file;
            // $add['bank_code'] = serialize($config['bank_code']);
            $add['config'] = serialize($config['config']);
            $add['config_value'] = '';
            $model->where($condition)->update($add);
        }
 
        if($row){
            $info['status'] = 1;
            $info['msg'] = $update['status'] ? '安装成功!' : '卸载成功!';
        }else{
            $info['status'] = 0;
            $info['msg'] = $update['status'] ? '安装失败' : '卸载失败';
        }        
        exit(json_encode($info));
    }

    /**
     * 参数配置
     * @return [type] [description]
     */
    public function setting(){
    	$condition['type'] = input('param.type');
        $condition['code'] = input('param.code');
        $model = M('plugin');
        $row = $model->where($condition)->find();
        if(!$row){
            exit($this->error("不存在该插件"));
        }

        $row['config'] = unserialize($row['config']);

        if(IS_POST){
            $config = I('post.config/a');
            //空格过滤
            $config = trim_array_element($config);
            if($config){
                $config = serialize($config);
            }
            $row = $model->where($condition)->update(array('config_value'=>$config));
            if($row){
                return json(msg(1, url('plugin/index'),'编辑成功'));
            }
            return json(msg(1, url('plugin/index'),'编辑失败'));
        }

        $this->assign('plugin',$row);
        $this->assign('config_value',unserialize($row['config_value']));
        return $this->fetch();
    }


    /**
     * 插件目录扫描
     * @return array 返回目录数组
     */
    private function scanPlugin(){
        $plugin_list = array();
        $plugin_list['payment'] = $this->dirscan(config('PAYMENT_PLUGIN_PATH'));
        $plugin_list['login'] = $this->dirscan(config('LOGIN_PLUGIN_PATH'));
        $plugin_list['function'] = $this->dirscan(config('FUNCTION_PLUGIN_PATH'));
        
        foreach($plugin_list as $k=>$v){
            foreach($v as $k2=>$v2){
 
                if(!file_exists(PLUGIN_PATH.$k.'/'.$v2.'/config.php'))
                    unset($plugin_list[$k][$k2]);
                else
                {
                    $plugin_list[$k][$v2] = include(PLUGIN_PATH.$k.'/'.$v2.'/config.php');
                    unset($plugin_list[$k][$k2]);                    
                }
            }
        }
        return $plugin_list;
    }

    /**
     * 获取插件目录列表
     * @param $dir
     * @return array
     */
    private function dirscan($dir){
        $dirArray = array();
        if (false != ($handle = opendir ( $dir ))) {
            $i=0;
            while ( false !== ($file = readdir ( $handle )) ) {
                //去掉"“.”、“..”以及带“.xxx”后缀的文件
                if ($file != "." && $file != ".."&&!strpos($file,".")) {
                    $dirArray[$i]=$file;
                    $i++;
                }
            }
            //关闭句柄
            closedir ( $handle );
        }
        return $dirArray;
    }

    /**
     * 更新插件到数据库
     * @param $plugin_list array 本地插件数组
     */
    private function insertPlugin($plugin_list){
       
        $save_path = UPLOAD_PATH.'logistics/';
        $source_path = PLUGIN_PATH . 'shipping/';

        $new_arr = array(); // 本地
        //插件类型
        foreach($plugin_list as $pt=>$pv){
            //  本地对比数据库
            foreach($pv as $t=>$v){
                $tmp['code'] = $v['code'];
                $tmp['type'] = $pt;
                $new_arr[] = $tmp;
                // 对比数据库 本地有 数据库没有
                $is_exit = db('plugin')->where(array('type'=>$pt,'code'=>$v['code']))->find();
                if(empty($is_exit)){
                   if($pt == 'shipping'){
                       @copy($source_path.$v['code'].'/'.$v['icon'], $save_path.$v['code'].'.jpg');
                       $add['icon'] = $v['icon'];
                   }else{ 
                        $add['icon'] = $v['icon'];
                    } 
                    $add['code'] = $v['code'];
                    $add['name'] = $v['name'];
                    $add['version'] = $v['version'];
                    $add['author'] = $v['author'];
                    $add['desc'] = $v['desc'];
                    // $add['bank_code'] = serialize($v['bank_code']);
                    $add['type'] = $pt;
                    $add['scene'] = $v['scene'];
                    $add['config'] = empty($v['config']) ? '' : serialize($v['config']);
                    db('plugin')->insert($add);
                }
            }
        }
        //数据库有 本地没有
//        foreach($d_list as $k=>$v){
//            if(!in_array($v,$new_arr)){
//                M('plugin')->where($v)->delete();
//            }
//        }

    }

  
    /**
     * 检查插件是否存在
     * @return mixed
     */
    private function checkExist(){
        $condition['type'] = I('get.type');
        $condition['code'] = I('get.code');

        $model = M('plugin');
        $row = $model->where($condition)->find();
        if(!$row && false){
            exit($this->error("不存在该插件"));
        }
        return $row;
    }
    
    public function check_str($str){
        //$pat ='/[a-zA-Z\x{4e00}-\x{9fa5}]*$/u';// '/^[a-zA-Z0-9_]*$/';
		$pat ='/[a-zA-Z\x{4e00}-\x{9fa5}]/u';// '/^[a-zA-Z0-9_]*$/';
        if(!preg_match( $pat, $str )){
            return  false;
        }
        return true;
    }

}